package sg.edu.nus.iss.cerberus.wizard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil;
import org.eclipse.jdt.internal.junit.BasicElementLabels;
import org.eclipse.jdt.internal.junit.JUnitCorePlugin;
import org.eclipse.jdt.internal.junit.Messages;
import org.eclipse.jdt.internal.junit.buildpath.BuildPathSupport;
import org.eclipse.jdt.internal.junit.ui.IJUnitHelpContextIds;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
import org.eclipse.jdt.internal.junit.util.JUnitStatus;
import org.eclipse.jdt.internal.junit.util.JUnitStubUtility;
import org.eclipse.jdt.internal.junit.util.LayoutUtil;
import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
import org.eclipse.jdt.internal.junit.wizards.MethodStubsSelectionButtonGroup;
import org.eclipse.jdt.internal.junit.wizards.WizardMessages;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
import org.eclipse.jdt.junit.wizards.NewTestCaseWizardPageTwo;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.wizards.NewTypeWizardPage;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.dialogs.SelectionDialog;

import sg.edu.nus.iss.cerberus.engine.JUnit4TestClassBuilder;
import sg.edu.nus.iss.cerberus.engine.JUnitMethodCheck;
import sg.edu.nus.iss.cerberus.engine.TestClassDirector;
import sg.edu.nus.iss.cerberus.engine.TestEngineParser;
import sg.edu.nus.iss.cerberus.model.CClass;
import sg.edu.nus.iss.cerberus.model.FixtureData;
import sg.edu.nus.iss.cerberus.model.MethodTestData;
import sg.edu.nus.iss.cerberus.model.TestGenerationData;
import sg.edu.nus.iss.cerberus.util.CerberusConstants;


@SuppressWarnings("restriction")
public class TestFixturePage extends NewTypeWizardPage
{    
    //private NewTestCaseWizardPageTwo fPage2;
    @SuppressWarnings("restriction")
	private MethodStubsSelectionButtonGroup fMethodStubsButtons;

    private String fClassUnderTestText; // model
    private IType fClassUnderTest; // resolved model, can be null

    private Text fClassUnderTestControl; // control
    private IStatus fClassUnderTestStatus; // status

    private Button fClassUnderTestButton;
    @SuppressWarnings("restriction")
	private JavaTypeCompletionProcessor fClassToTestCompletionProcessor;

    // private Button fJUnit4Toggle;
    private boolean fIsJunit4;
    private IStatus fJunit4Status; // status
    //private boolean fIsJunit4Enabled;
    private Link fLink;
    private Label fImage;

    //private Button junti3Toggle;
    private Button unit4Toggle;
    //private Button testNgToggle;

//    private Preferences preferences;
    private IJavaProject javaProject;
    private IStructuredSelection selection;
    
   private JUnitMethodCheck assertionCheck;    
   	private TestGenerationData testGenData;
   	
   	public void setTestGenData(TestGenerationData testGenData){
   		this.testGenData = testGenData;
   	}
   	
    public TestGenerationData getTestGenData() {
		return testGenData;
	}

	CClass classobj = null;
   
    
    @SuppressWarnings("restriction")
	public TestFixturePage(NewTestCaseWizardPageTwo page2,  IJavaProject javaProject)
    {
        super(true, CerberusConstants.PAGE_NAME);
//        this.preferences = preferences;
        this.javaProject = javaProject;

        //fPage2 = page2;

        //setTitle(WizardMessages.NewTestCaseWizardPageOne_title);
        setTitle("Cerberus Unit Test");
        //setDescription(WizardMessages.NewTestCaseWizardPageOne_description);
        setDescription(CerberusConstants.WIZ_PAGE_ONE_DESCRIPTION);
        
        String[] buttonNames = new String[] {
        /* IDX_SETUP_CLASS */WizardMessages.NewTestCaseWizardPageOne_methodStub_setUpBeforeClass,
        /* IDX_TEARDOWN_CLASS */WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDownAfterClass,
        /* IDX_SETUP */WizardMessages.NewTestCaseWizardPageOne_methodStub_setUp,
        /* IDX_TEARDOWN */WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDown,
        /* IDX_CONSTRUCTOR */
        //WizardMessages.NewTestCaseWizardPageOne_methodStub_constructor 
        };
        enableCommentControl(true);

        fMethodStubsButtons = new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 2);
        fMethodStubsButtons.setLabelText(WizardMessages.NewTestCaseWizardPageOne_method_Stub_label);

        fClassToTestCompletionProcessor = new JavaTypeCompletionProcessor(false, false, true);

        fClassUnderTestStatus = new JUnitStatus();

        fClassUnderTestText = ""; //$NON-NLS-1$

        fJunit4Status = new JUnitStatus();
        fIsJunit4 = false;
        
    }
    
    public TestFixturePage(IJavaProject javaProject)
    {
        super(true, CerberusConstants.PAGE_NAME);
        this.javaProject = javaProject;
        setTitle("Cerberus Unit Test");
        setDescription(CerberusConstants.WIZ_PAGE_ONE_DESCRIPTION);    
        
        String[] buttonNames = new String[] {
        /* IDX_SETUP_CLASS */WizardMessages.NewTestCaseWizardPageOne_methodStub_setUpBeforeClass,
        /* IDX_TEARDOWN_CLASS */WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDownAfterClass,
        /* IDX_SETUP */WizardMessages.NewTestCaseWizardPageOne_methodStub_setUp,
        /* IDX_TEARDOWN */WizardMessages.NewTestCaseWizardPageOne_methodStub_tearDown,
        /* IDX_CONSTRUCTOR */
        //WizardMessages.NewTestCaseWizardPageOne_methodStub_constructor 
        };
        enableCommentControl(true);

        fMethodStubsButtons = new MethodStubsSelectionButtonGroup(SWT.CHECK, buttonNames, 2);
        fMethodStubsButtons.setLabelText(WizardMessages.NewTestCaseWizardPageOne_method_Stub_label);

        fClassToTestCompletionProcessor = new JavaTypeCompletionProcessor(false, false, true);

        fClassUnderTestStatus = new JUnitStatus();

        fClassUnderTestText = ""; //$NON-NLS-1$

        fJunit4Status = new JUnitStatus();
        fIsJunit4 = false;
        assertionCheck = new JUnitMethodCheck();
        testGenData= new TestGenerationData();
    }

    public IStructuredSelection getSelection(){
    	return this.selection;
    }
    
    /**
     * Initialized the page with the current selection
     * 
     * @param selection The selection
     */
    @SuppressWarnings("restriction")
	public void init(IStructuredSelection selection)
    {
        this.selection = selection;
    	
    	IJavaElement element = getInitialJavaElement(selection);

        initContainerPage(element);
        initTypePage(element);
        
        // put default class to test
        if(element != null)
        {
            IType classToTest = null;
            // evaluate the enclosing type
            IType typeInCompUnit = (IType) element.getAncestor(IJavaElement.TYPE);
            if(typeInCompUnit != null)
            {
            	classobj = new TestEngineParser(javaProject, typeInCompUnit).parseCompilationUnit();
            	testGenData.setCut(classobj);
            	if(typeInCompUnit.getCompilationUnit() != null)
                {
                    classToTest = typeInCompUnit;
                }
            }
            else
            {
                ICompilationUnit cu = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
                if(cu != null)
                    classToTest = cu.findPrimaryType();
                else
                {
                    if(element instanceof IClassFile)
                    {
                        try
                        {
                            IClassFile cf = (IClassFile) element;
                            if(cf.isStructureKnown())
                                classToTest = cf.getType();
                        }
                        catch (JavaModelException e)
                        {
                            JUnitPlugin.log(e);
                        }
                    }
                }
            }
            if(classToTest != null)
            {
                try
                {
                    if(! TestSearchEngine.isTestImplementor(classToTest))
                    {
                        setClassUnderTest(classToTest.getFullyQualifiedName('.'));
                    }
                }
                catch (JavaModelException e)
                {
                    JUnitCorePlugin.log(e);
                }
            }
        }

        restoreWidgetValues();

        boolean isJunit4 = false;
        if(element != null && element.getElementType() != IJavaElement.JAVA_MODEL)
        {
            IJavaProject project = element.getJavaProject();
            try
            {
                isJunit4 = project.findType(JUnitCorePlugin.JUNIT4_ANNOTATION_NAME) != null;
            }
            catch (JavaModelException e)
            {
            	e.printStackTrace();

            }
        }
        setJUnit4(isJunit4, true);

        updateStatus(getStatusList());
    }

    @SuppressWarnings("restriction")
	private IStatus junit4Changed()
    {
        JUnitStatus status = new JUnitStatus();
        return status;
    }

    /**
     * Specifies if the test should be created as JUnit 4 test.
     * 
     * @param isJUnit4 If set, a Junit 4 test will be created
     * @param isEnabled if <code>true</code> the modifier fields are editable;
     *            otherwise they are read-only
     * @since 3.2
     */
    public void setJUnit4(boolean isJUnit4, boolean isEnabled)
    {
        if(unit4Toggle != null && ! unit4Toggle.isDisposed())
        {
            unit4Toggle.setSelection(isJUnit4);
            unit4Toggle.setEnabled(isEnabled);
        }
        internalSetJUnit4(isJUnit4);
    }

    /**
     * Returns <code>true</code> if the test should be created as Junit 4 test
     * 
     * @return returns <code>true</code> if the test should be created as Junit
     *         4 test
     * @since 3.2
     */
    public boolean isJUnit4()
    {
        return fIsJunit4;
    }

    @SuppressWarnings("restriction")
	private void internalSetJUnit4(boolean isJUnit4)
    {
        fIsJunit4 = isJUnit4;
        fJunit4Status = junit4Changed();
        if(fIsJunit4)
        {
            setSuperClass("java.lang.Object", false); //$NON-NLS-1$
        }
        else
        {
            setSuperClass(JUnitCorePlugin.TEST_SUPERCLASS_NAME, true);
        }
        handleFieldChanged(CerberusConstants.JUNIT4TOGGLE);
    }

    /*
     * (non-Javadoc)
     * @see
     * org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(
     * String)
     */
    @SuppressWarnings("restriction")
	protected void handleFieldChanged(String fieldName)
    {
        super.handleFieldChanged(fieldName);
        if(fieldName.equals(CONTAINER))
        {
            fClassUnderTestStatus = classUnderTestChanged();
            if(fClassUnderTestButton != null && ! fClassUnderTestButton.isDisposed())
            {
                fClassUnderTestButton.setEnabled(getPackageFragmentRoot() != null);
            }
            fJunit4Status = junit4Changed();

            updateBuildPathMessage();
        }
        else if(fieldName.equals(CerberusConstants.JUNIT4TOGGLE))
        {
            updateBuildPathMessage();
            fMethodStubsButtons.setEnabled(CerberusConstants.IDX_SETUP_CLASS, isJUnit4());
            fMethodStubsButtons.setEnabled(CerberusConstants.IDX_TEARDOWN_CLASS, isJUnit4());
          //  fMethodStubsButtons.setEnabled(IDX_CONSTRUCTOR,  isJUnit4());
        }
        updateStatus(getStatusList());
    }

    /**
     * Returns all status to be consider for the validation. Clients can
     * override.
     * 
     * @return The list of status to consider for the validation.
     */
    protected IStatus[] getStatusList()
    {
        return new IStatus[] { fContainerStatus, fPackageStatus, fTypeNameStatus, fClassUnderTestStatus, fModifierStatus, fSuperClassStatus, fJunit4Status };
    }

    /*
    private boolean isTestNgSelected()
    {
        return testNgToggle != null && testNgToggle.getSelection();
    }
	*/
    /*
     * (non-Javadoc)
     * @see
     * org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets
     * .Composite)
     */
    @SuppressWarnings("restriction")
	public void createControl(Composite parent)
    {
        initializeDialogUnits(parent);

        Composite composite = new Composite(parent, SWT.NONE);

        int nColumns = 4;

        GridLayout layout = new GridLayout();
        layout.numColumns = nColumns;
        composite.setLayout(layout);
        setTitle(CerberusConstants.WIZARD_TITLE_TEXT);
        //createJUnit4Controls(composite, nColumns);
        createContainerControls(composite, nColumns);
        createPackageControls(composite, nColumns);
        createSeparator(composite, nColumns);
        createTypeNameControls(composite, nColumns);
        createSuperClassControls(composite, nColumns);
        createMethodStubSelectionControls(composite, nColumns);
        createCommentControls(composite, nColumns);
        createSeparator(composite, nColumns);
        createClassUnderTestControls(composite, nColumns);
        createSeparator(composite, nColumns);
        createBuildPathConfigureControls(composite, nColumns);

        setControl(composite);

        // set default and focus
        String classUnderTest = getClassUnderTestText();
        if(classUnderTest.length() > 0)
        {
            setTypeName(Signature.getSimpleName(classUnderTest) + CerberusConstants.TEST_SUFFIX, true);
        }

        Dialog.applyDialogFont(composite);
        PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJUnitHelpContextIds.NEW_TESTCASE_WIZARD_PAGE);

        setFocus();
    }

    /**
     * Creates the controls for the method stub selection buttons. Expects a
     * <code>GridLayout</code> with at least 3 columns.
     * 
     * @param composite the parent composite
     * @param nColumns number of columns to span
     */
    @SuppressWarnings("restriction")
	protected void createMethodStubSelectionControls(Composite composite, int nColumns)
    {
        LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getLabelControl(composite), nColumns);
        LayoutUtil.createEmptySpace(composite, 1);
        LayoutUtil.setHorizontalSpan(fMethodStubsButtons.getSelectionButtonsGroup(composite), nColumns - 1);
    }
    

    /**
     * Creates the controls for the 'class under test' field. Expects a
     * <code>GridLayout</code> with at least 3 columns.
     * 
     * @param composite the parent composite
     * @param nColumns number of columns to span
     */
    protected void createClassUnderTestControls(Composite composite, int nColumns)
    {
        Label classUnderTestLabel = new Label(composite, SWT.LEFT | SWT.WRAP);
        classUnderTestLabel.setFont(composite.getFont());
        classUnderTestLabel.setText(WizardMessages.NewTestCaseWizardPageOne_class_to_test_label);
        classUnderTestLabel.setLayoutData(new GridData());

        fClassUnderTestControl = new Text(composite, SWT.SINGLE | SWT.BORDER);
        fClassUnderTestControl.setEnabled(true);
        fClassUnderTestControl.setFont(composite.getFont());
        fClassUnderTestControl.setText(fClassUnderTestText);
        fClassUnderTestControl.addModifyListener(new ModifyListener()
        {
            public void modifyText(ModifyEvent e)
            {
                internalSetClassUnderText(((Text) e.widget).getText());
            }
        });
        GridData gd = new GridData();
        gd.horizontalAlignment = GridData.FILL;
        gd.grabExcessHorizontalSpace = true;
        gd.horizontalSpan = nColumns - 2;
        fClassUnderTestControl.setLayoutData(gd);

        fClassUnderTestButton = new Button(composite, SWT.PUSH);
        fClassUnderTestButton.setText(WizardMessages.NewTestCaseWizardPageOne_class_to_test_browse);
        fClassUnderTestButton.setEnabled(true);
        fClassUnderTestButton.addSelectionListener(new SelectionListener()
        {
            public void widgetDefaultSelected(SelectionEvent e)
            {
                classToTestButtonPressed();
            }

            public void widgetSelected(SelectionEvent e)
            {
                classToTestButtonPressed();
            }
        });
        gd = new GridData();
        gd.horizontalAlignment = GridData.FILL;
        gd.grabExcessHorizontalSpace = false;
        gd.horizontalSpan = 1;
        gd.widthHint = LayoutUtil.getButtonWidthHint(fClassUnderTestButton);
        fClassUnderTestButton.setLayoutData(gd);

        ControlContentAssistHelper.createTextContentAssistant(fClassUnderTestControl, fClassToTestCompletionProcessor);
    }

    /**
     * Creates the controls for the JUnit 4 toggle control. Expects a
     * <code>GridLayout</code> with at least 3 columns.
     * 
     * @param composite the parent composite
     * @param nColumns number of columns to span
     * @since 3.2
     */
    protected void createJUnit4Controls(Composite composite, int nColumns)
    {
        /*
         * Composite inner= new Composite(composite, SWT.NONE);
         * inner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
         * nColumns, 1)); GridLayout layout= new GridLayout(2, false);
         * layout.marginHeight= 0; layout.marginWidth= 0;
         * inner.setLayout(layout); SelectionAdapter listener= new
         * SelectionAdapter() { public void widgetSelected(SelectionEvent e) {
         * boolean isSelected= ((Button) e.widget).getSelection();
         * internalSetJUnit4(isSelected); } }; Button junti3Toggle= new
         * Button(inner, SWT.RADIO);junti3Toggle.setText(WizardMessages.
         * NewTestCaseWizardPageOne_junit3_radio_label);
         * junti3Toggle.setLayoutData(new GridData(GridData.FILL,
         * GridData.CENTER, false, false, 1, 1));
         * junti3Toggle.setSelection(!fIsJunit4);
         * junti3Toggle.setEnabled(fIsJunit4Enabled); fJUnit4Toggle= new
         * Button(inner, SWT.RADIO);fJUnit4Toggle.setText(WizardMessages.
         * NewTestCaseWizardPageOne_junit4_radio_label);
         * fJUnit4Toggle.setSelection(fIsJunit4);
         * fJUnit4Toggle.setEnabled(fIsJunit4Enabled);
         * fJUnit4Toggle.setLayoutData(new GridData(GridData.FILL,
         * GridData.CENTER, false, false, 1, 1));
         * fJUnit4Toggle.addSelectionListener(listener);
         */
        Composite inner = new Composite(composite, SWT.NONE);
        inner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, nColumns, 1));
        GridLayout layout = new GridLayout(3, false);
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        inner.setLayout(layout);

        /*
        SelectionAdapter listener = new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                testTypeSelectionChanged();
            }
        };
		*/
    }
    
    /*
    private void testTypeSelectionChanged()
    {
        setJUnit4(true, true);
        setSuperClass("cerberus.test_superclass", true);
    }
	*/
    
    /**
     * Creates the controls for the JUnit 4 toggle control. Expects a
     * <code>GridLayout</code> with at least 3 columns.
     * 
     * @param composite the parent composite
     * @param nColumns number of columns to span
     * @since 3.2
     */
    protected void createBuildPathConfigureControls(Composite composite, int nColumns)
    {
        Composite inner = new Composite(composite, SWT.NONE);
        inner.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false, nColumns, 1));
        GridLayout layout = new GridLayout(2, false);
        layout.marginWidth = 0;
        layout.marginHeight = 0;
        inner.setLayout(layout);

        fImage = new Label(inner, SWT.NONE);
        fImage.setImage(JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING));
        fImage.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1));

        fLink = new Link(inner, SWT.WRAP);
        fLink.setText("\n\n"); //$NON-NLS-1$
        fLink.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent e)
            {
                performBuildpathConfiguration(e.text);
            }
        });
        GridData gd = new GridData(GridData.FILL, GridData.BEGINNING, true, false, 1, 1);
        gd.widthHint = convertWidthInCharsToPixels(60);
        fLink.setLayoutData(gd);
        updateBuildPathMessage();
    }

    private void performBuildpathConfiguration(Object data)
    {
        IPackageFragmentRoot root = getPackageFragmentRoot();
        if(root == null)
        {
            return; // should not happen. Link shouldn't be visible
        }
        IJavaProject javaProject = root.getJavaProject();

        /*
        if("a3".equals(data)) { // add and configure JUnit 3 //$NON-NLS-1$
            String id = BUILD_PATH_PAGE_ID;
            Map<Object, Object> input = new HashMap<Object, Object>();
            IClasspathEntry newEntry = BuildPathSupport.getJUnit3ClasspathEntry();
            input.put(BUILD_PATH_KEY_ADD_ENTRY, newEntry);
            input.put(BUILD_PATH_BLOCK, Boolean.TRUE);
            PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, id, new String[] { id }, input).open();
        }*/
        if("a4".equals(data)) { // add and configure JUnit 4 //$NON-NLS-1$
            String id = CerberusConstants.BUILD_PATH_PAGE_ID;
            Map<Object, Object> input = new HashMap<Object, Object>();
            IClasspathEntry newEntry = BuildPathSupport.getJUnit4ClasspathEntry();
            input.put(CerberusConstants.BUILD_PATH_KEY_ADD_ENTRY, newEntry);
            input.put(CerberusConstants.BUILD_PATH_BLOCK, Boolean.TRUE);
            PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, id, new String[] { id }, input).open();
        }
        else if("b".equals(data)) { // open build path //$NON-NLS-1$
            String id = CerberusConstants.BUILD_PATH_PAGE_ID;
            Map<Object, Object> input = new HashMap<Object, Object>();
            input.put(CerberusConstants.BUILD_PATH_BLOCK, Boolean.TRUE);
            PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, id, new String[] { id }, input).open();
        }
        else if("c".equals(data)) { // open compliance //$NON-NLS-1$
            String buildPath = CerberusConstants.BUILD_PATH_PAGE_ID;
            String complianceId = CerberusConstants.COMPLIANCE_PAGE_ID;
            Map<Object, Object> input = new HashMap<Object, Object>();
            input.put(CerberusConstants.BUILD_PATH_BLOCK, Boolean.TRUE);
            input.put(CerberusConstants.KEY_NO_LINK, Boolean.TRUE);
            PreferencesUtil.createPropertyDialogOn(getShell(), javaProject, complianceId, new String[] { buildPath, complianceId }, data).open();
        }

        updateBuildPathMessage();
    }

    private void updateBuildPathMessage()
    {
        if(fLink == null || fLink.isDisposed())
        {
            return;
        }

        String message = null;
        IPackageFragmentRoot root = getPackageFragmentRoot();
        if(root != null)
        {
            IJavaProject project = root.getJavaProject();
            if(project.exists())
            {
                if(isJUnit4())
                {
                    if(! JUnitStubUtility.is50OrHigher(project))
                    {
                        message = WizardMessages.NewTestCaseWizardPageOne_linkedtext_java5required;
                    }
                }
            }
        }
        fLink.setVisible(message != null);
        fImage.setVisible(message != null);

        if(message != null)
        {
            fLink.setText(message);
        }
    }

    private void classToTestButtonPressed()
    {
        IType type = chooseClassToTestType();
        if(type != null)
        {
            setClassUnderTest(type.getFullyQualifiedName('.'));
        }
    }

    private IType chooseClassToTestType()
    {
        IPackageFragmentRoot root = getPackageFragmentRoot();
        if(root == null)
            return null;

        IJavaElement[] elements = new IJavaElement[] { root.getJavaProject() };
        IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements);

        try
        {
            SelectionDialog dialog = JavaUI.createTypeDialog(getShell(), getWizard().getContainer(), scope, IJavaElementSearchConstants.CONSIDER_CLASSES_AND_ENUMS, false, getClassUnderTestText());
            dialog.setTitle(WizardMessages.NewTestCaseWizardPageOne_class_to_test_dialog_title);
            dialog.setMessage(WizardMessages.NewTestCaseWizardPageOne_class_to_test_dialog_message);
            if(dialog.open() == Window.OK)
            {
                Object[] resultArray = dialog.getResult();
                if(resultArray != null && resultArray.length > 0)
                    return (IType) resultArray[0];
            }
        }
        catch (JavaModelException e)
        {
            JUnitPlugin.log(e);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.jdt.ui.wizards.NewTypeWizardPage#packageChanged()
     */
    protected IStatus packageChanged()
    {
        IStatus status = super.packageChanged();
        fClassToTestCompletionProcessor.setPackageFragment(getPackageFragment());
        return status;
    }

    /**
     * Hook method that gets called when the class under test has changed. The
     * method class under test returns the status of the validation.
     * <p>
     * Subclasses may extend this method to perform their own validation.
     * </p>
     * 
     * @return the status of the validation
     */
    protected IStatus classUnderTestChanged()
    {
        JUnitStatus status = new JUnitStatus();

        fClassUnderTest = null;

        IPackageFragmentRoot root = getPackageFragmentRoot();
        if(root == null)
        {
            return status;
        }

        String classToTestName = getClassUnderTestText();
        if(classToTestName.length() == 0)
        {
            return status;
        }

        IStatus val = JavaConventionsUtil.validateJavaTypeName(classToTestName, root);
        if(val.getSeverity() == IStatus.ERROR)
        {
            status.setError(WizardMessages.NewTestCaseWizardPageOne_error_class_to_test_not_valid);
            return status;
        }

        IPackageFragment pack = getPackageFragment(); // can be null
        try
        {
            IType type = resolveClassNameToType(root.getJavaProject(), pack, classToTestName);
            if(type == null)
            {
                status.setError(WizardMessages.NewTestCaseWizardPageOne_error_class_to_test_not_exist);
                return status;
            }
            if(type.isInterface())
            {
                status.setWarning(Messages.format(WizardMessages.NewTestCaseWizardPageOne_warning_class_to_test_is_interface, BasicElementLabels.getJavaElementName(classToTestName)));
            }

            if(pack != null && ! JUnitStubUtility.isVisible(type, pack))
            {
                status.setWarning(Messages.format(WizardMessages.NewTestCaseWizardPageOne_warning_class_to_test_not_visible, BasicElementLabels.getJavaElementName(classToTestName)));
            }
            fClassUnderTest = type;
            //fPage2.setClassUnderTest(fClassUnderTest);
            
        }
        catch (JavaModelException e)
        {
            status.setError(WizardMessages.NewTestCaseWizardPageOne_error_class_to_test_not_valid);
        }
        return status;
    }

    /**
     * Returns the content of the class to test text field.
     * 
     * @return the name of the class to test
     */
    public String getClassUnderTestText()
    {
        return fClassUnderTestText;
    }

    /**
     * Returns the class to be tested.
     * 
     * @return the class under test or <code>null</code> if the entered values
     *         are not valid
     */
    public IType getClassUnderTest()
    {
        return fClassUnderTest;
    }

    /**
     * Sets the name of the class under test.
     * 
     * @param name The name to set
     */
    public void setClassUnderTest(String name)
    {
        if(fClassUnderTestControl != null && ! fClassUnderTestControl.isDisposed())
        {
            fClassUnderTestControl.setText(name);
        }
        internalSetClassUnderText(name);
    }

    private void internalSetClassUnderText(String name)
    {
        fClassUnderTestText = name;
        fClassUnderTestStatus = classUnderTestChanged();
        handleFieldChanged(CerberusConstants.CLASS_UNDER_TEST);
    }
    /*
     * (non-Javadoc)
     * @see
     * org.eclipse.jdt.ui.wizards.NewTypeWizardPage#createTypeMembers(org.eclipse
     * .jdt.core.IType,
     * org.eclipse.jdt.ui.wizards.NewTypeWizardPage.ImportsManager,
     * org.eclipse.core.runtime.IProgressMonitor)
     */
    protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException
    {
    	JUnitMethodCheck jcheck=null;
    	FixtureData fixD=null;
    	TestClassDirector testdir=null;
        try{
        	
        	 fixD= new FixtureData();
        	
        	
		//if(fMethodStubsButtons.isSelected(IDX_CONSTRUCTOR))
		//  createConstructor(type, imports);
        	
		 if(fMethodStubsButtons.isSelected( CerberusConstants.IDX_SETUP_CLASS))
	     	fixD.setAssertionData(CerberusConstants.SETUP_CLASS );
	     if(fMethodStubsButtons.isSelected(CerberusConstants.IDX_TEARDOWN_CLASS))
	     	fixD.setAssertionData(CerberusConstants.TEARDOWN_CLASS);
	     if(fMethodStubsButtons.isSelected(CerberusConstants.IDX_SETUP))
	     	fixD.setAssertionData(CerberusConstants.SETUP);
	     if(fMethodStubsButtons.isSelected(CerberusConstants.IDX_TEARDOWN))
	     	fixD.setAssertionData(CerberusConstants.TEARDOWN);
        
        imports.addStaticImport("org.junit.Assert", "*", false);
        JUnit4TestClassBuilder builder=new JUnit4TestClassBuilder();
    	testdir=new TestClassDirector(builder);
    	
     	testGenData.setFixtureData(fixD);
     	testGenData.setType(type);
     	testGenData.setClassUnderTest(getClassUnderTest());
     	testGenData.setImports(imports); 
     	testGenData.setAddcomment(isAddComments());
     	testGenData.setTypeName(getTypeName());
     	testGenData.setPackageFragment(getPackageFragment());
    	
    	testdir.createTestClass(testGenData);
     
        }
        catch(Exception e)
        {
        	e.printStackTrace();

        	
        }
    }


    /*
     * (non-Javadoc)
     * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
     */
    public void setVisible(boolean visible)
    {
        super.setVisible(visible);
        if(! visible)
        {
            saveWidgetValues();
        }

        // if (visible) setFocus();
    }

    /**
     * The method is called when the container has changed to validate if the
     * project is suited for the JUnit test class. Clients can override to
     * modify or remove that validation.
     * 
     * @return the status of the validation
     */
    protected IStatus validateIfJUnitProject()
    {
        JUnitStatus status = new JUnitStatus();
        IPackageFragmentRoot root = getPackageFragmentRoot();
        if(root != null)
        {
            try
            {
                IJavaProject project = root.getJavaProject();
                if(project.exists())
                {
                    if(isJUnit4())
                    {
                        if(! JUnitStubUtility.is50OrHigher(project))
                        {
                            status.setError(WizardMessages.NewTestCaseWizardPageOne_error_java5required);
                            return status;
                        }
                        if(project.findType(JUnitCorePlugin.JUNIT4_ANNOTATION_NAME) == null)
                        {
                            status.setWarning(WizardMessages.NewTestCaseWizardPageOne__error_junit4NotOnbuildpath);
                            return status;
                        }
                    }
                    else
                    {
                        if(project.findType(JUnitCorePlugin.TEST_SUPERCLASS_NAME) == null)
                        {
                            status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_junitNotOnbuildpath);
                            return status;
                        }
                    }
                }
            }
            catch (JavaModelException e)
            {
            }
        }
        return status;
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.jdt.ui.wizards.NewTypeWizardPage#superClassChanged()
     */
    protected IStatus superClassChanged()
    {
        // replaces the super class validation of of the normal type wizard
    	return new JUnitStatus();
    	/*
    	if(isJUnit4())//isJUnit4() || isTestNgSelected()
        {
            return new JUnitStatus();
        }
		
        String superClassName = getSuperClass();
        JUnitStatus status = new JUnitStatus();
        if(superClassName == null || superClassName.trim().equals("")) { //$NON-NLS-1$
            status.setError(WizardMessages.NewTestCaseWizardPageOne_error_superclass_empty);
            return status;
        }
        if(getPackageFragmentRoot() != null)
        {
            try
            {
                IType type = resolveClassNameToType(getPackageFragmentRoot().getJavaProject(), getPackageFragment(), superClassName);
                if(type == null)
                {
                    status.setWarning(WizardMessages.NewTestCaseWizardPageOne_error_superclass_not_exist);
                    return status;
                }
                if(type.isInterface())
                {
                    status.setError(WizardMessages.NewTestCaseWizardPageOne_error_superclass_is_interface);
                    return status;
                }
                if(! TestSearchEngine.isTestImplementor(type))
                {
                    status.setError(Messages.format(WizardMessages.NewTestCaseWizardPageOne_error_superclass_not_implementing_test_interface, BasicElementLabels.getJavaElementName(JUnitCorePlugin.TEST_INTERFACE_NAME)));
                    return status;
                }
            }
            catch (JavaModelException e)
            {
                JUnitPlugin.log(e);
            }
        }
        return status;*/
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.jface.wizard.IWizardPage#canFlipToNextPage()
     */
    public boolean canFlipToNextPage()
    {
        return super.canFlipToNextPage() && getClassUnderTest() != null;
    }

    private IType resolveClassNameToType(IJavaProject jproject, IPackageFragment pack, String classToTestName) throws JavaModelException
    {
        if(! jproject.exists())
        {
            return null;
        }

        IType type = jproject.findType(classToTestName);

        // search in current package
        if(type == null && pack != null && ! pack.isDefaultPackage())
        {
            type = jproject.findType(pack.getElementName(), classToTestName);
        }

        // search in java.lang
        if(type == null)
        {
            type = jproject.findType("java.lang", classToTestName); //$NON-NLS-1$
        }
        return type;
    }

    /**
     * Use the dialog store to restore widget values to the values that they
     * held last time this wizard was used to completion
     */
    private void restoreWidgetValues()
    {
        IDialogSettings settings = getDialogSettings();
        if(settings != null)
        {
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_SETUP, settings.getBoolean(CerberusConstants.STORE_SETUP));
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_TEARDOWN, settings.getBoolean(CerberusConstants.STORE_TEARDOWN));
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_SETUP_CLASS, settings.getBoolean(CerberusConstants.STORE_SETUP_CLASS));
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_TEARDOWN_CLASS, settings.getBoolean(CerberusConstants.STORE_TEARDOWN_CLASS));
           // fMethodStubsButtons.setSelection(IDX_CONSTRUCTOR, settings.getBoolean(STORE_CONSTRUCTOR));
        }
        else
        {
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_SETUP, false); // setUp
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_TEARDOWN, false); // tearDown
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_SETUP_CLASS, false); // setUpBeforeClass
            fMethodStubsButtons.setSelection(CerberusConstants.IDX_TEARDOWN_CLASS, false); // setUpAfterClass
           // fMethodStubsButtons.setSelection(IDX_CONSTRUCTOR, false); // constructor
        }
    }

    /**
     * Since Finish was pressed, write widget values to the dialog store so that
     * they will persist into the next invocation of this wizard page
     */
    private void saveWidgetValues()
    {
        IDialogSettings settings = getDialogSettings();
        if(settings != null)
        {
            settings.put(CerberusConstants.STORE_SETUP, fMethodStubsButtons.isSelected(CerberusConstants.IDX_SETUP));
            settings.put(CerberusConstants.STORE_TEARDOWN, fMethodStubsButtons.isSelected(CerberusConstants.IDX_TEARDOWN));
            settings.put(CerberusConstants.STORE_SETUP_CLASS, fMethodStubsButtons.isSelected(CerberusConstants.IDX_SETUP_CLASS));
            settings.put(CerberusConstants.STORE_TEARDOWN_CLASS, fMethodStubsButtons.isSelected(CerberusConstants.IDX_TEARDOWN_CLASS));
           // settings.put(STORE_CONSTRUCTOR, fMethodStubsButtons.isSelected(IDX_CONSTRUCTOR));
        }
    }
}
